$(function() {
    var  baseurl = $("#_ctx").val();

    $(".select-popup input").one("mouseover",function(){
        getMenu();
    })


    function getMenu(){
        $.ajax({
            method : 'get',
            dataType: 'json',
            url:  baseurl + '/outdoor/category/json?parentId=0',
            success: function (data) {
                console.log(data);
                var selectOnoff = true;
                initMenu(data,$(".select-menu"));
                $('.select-popup').on('click',function(){
                    if(selectOnoff){$(".select-menu").show();selectOnoff=!selectOnoff;}else{$(".select-menu").hide();selectOnoff=!selectOnoff;}
                });
                $(".select-menu").on('click', 'li p', function() {
                    var selectVal = $(this).find('span').text();
                    var dataId = $(this).attr('id');
                    $('.select-popup input').val(selectVal);
                    $("#categoryId").val(dataId);
                    $(".select-menu").hide();selectOnoff=!selectOnoff;
                    $(".menu-open .menu-item-child").hide();
                })

                $(".menu-open").on('mouseover', function() {
                    var $this = $(this);
                    var checkElement = $this.children('ul');
                    if ((checkElement.is('.menu-item-child')) && (!checkElement.is(':visible'))) {checkElement.show(); }
                });
                $(".menu-open").on('mouseout', function() {
                    var $this = $(this);
                    var checkElement = $this.children('ul');
                    if ((checkElement.is('.menu-item-child')) && (checkElement.is(':visible'))) { checkElement.hide();}
                });
            },
            error: function(){
                layer.alert('系统错误', {
                    icon : 5
                });
            }
        });
    }

    function initMenu(menu,parent){
        for(var i=0; i<menu.length; i++){
            var item = menu[i];
            var str = "";
            if(item.children == ""){
                str = "<li><p id='"+item.id+"'><span>"+item.name+"</span></p></li>";
                $(parent).append(str);
            }else{
                str = "<li class='menu-open'><p id='"+item.id+"'><i class='fa fa-plus-square'></i><span>"+item.name+"</span></p>";
                str +="<ul class='menu-item-child' id='menu-child-"+item.id+"'></ul></li>";
                $(parent).append(str);
                var childParent = $("#menu-child-"+item.id);
                initMenu(item.children,childParent);
            }
        }
    }
});
